package com.zzyl.nursing.service.member.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.member.FamilyMember;
import com.zzyl.nursing.dto.member.UserLoginDto;
import com.zzyl.nursing.mapper.member.FamilyMemberMapper;
import com.zzyl.nursing.service.member.IFamilyMemberService;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.serve.service.IWecharService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 老人家属Service业务层处理
 *
 * @author zzyl
 * @date 2025-10-22
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private IWecharService wecharService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }


    private List<String> userNameList = Arrays.asList("三阳开泰", "花开花落", "大大大大", "花开富贵", "姬霓太美", "基尼太美");


    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public LoginVo login(UserLoginDto dto) {
        // 获取用户openId
        String openId = wecharService.getOpenId(dto.getCode());
        if (StrUtil.isBlank(openId)) {
            throw new BaseException("获取openID错误");
        }


        // 判断数据库是否存在该用户
        FamilyMember familyMember = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        if (ObjectUtil.isEmpty(familyMember)) {
            // 打乱名字集合
            Collections.shuffle(userNameList);
            String userName = userNameList.get(0) + RandomUtil.randomNumbers(4);
            familyMember = FamilyMember.builder()
                    .openId(openId)
                    .name(userName)
                    .build();
            // 不存在新增用户
            this.save(familyMember);
        }
        // 判断手机号是否为空
        if (StringUtils.isBlank(familyMember.getPhone())) {
            // 补充手机号
            String phone = wecharService.getPhone(dto.getPhoneCode());
            this.lambdaUpdate().eq(FamilyMember::getId, familyMember.getId())
                    .set(FamilyMember::getPhone, phone)
                    .update();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", familyMember.getId());
        map.put("nickName", familyMember.getName());
        String token = tokenService.createToken(map);

        // 返回
        LoginVo loginVo = LoginVo.builder()
                .token(token)
                .nickName(familyMember.getName())
                .build();

        return loginVo;
    }
}
